// pages/upload-progress-listening/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 选择本地相册图片
  navToalbum() {
    wx.chooseMedia({
      // 最多可以选择的文件个数，基础库2.25.0前，最多可支持9个文件，2.25.0及以后最多可支持20个文件
      count: 20,
      mediaType: ['image', 'video', 'mix'],
      sourceType: ['album'],
      // 是否压缩所选文件，基础库2.25.0前仅对 mediaType 为 image 时有效，2.25.0及以后对全量 mediaType 有效
      sizeType: ['original'],
      maxDuration: 30,
      success: (res) => {
        console.log(res);
        // this.data.uploadList = res.tempFiles.map(item => {
        //   return {
        //     ...item,
        //     progress: 0
        //   }
        // })
        this.setData({
          uploadList: res.tempFiles.map(item => {
            return {
              ...item,
              progress: 0
            }
          })
        }, () => {
          this.uploadFiles()
        })
        app.globalData.uploadList = res.tempFiles
        // 进行上传到后台操作
        
      },
      fail: err => {
        console.log('chooseMedia', err)
      }
    })
  },

  /**
   * 提交文件到后台计算
   */
  uploadFiles(){
    const uploadList = this.data.uploadList
    uploadList.forEach((tempFileItem, index) => {
      // 获取文件名称
      const tempFilePathArr = tempFileItem.tempFilePath.split('/')
      const formData = {
        // sn: '', // 暂时不需要 20240722
        savePath: tempFilePathArr[tempFilePathArr.length - 1]
      }
      this.uploadPicResponse('http://nasbackend.natapp1.cc/nas/api/v1/mini/file/check', tempFileItem.tempFilePath, index, formData)
    })
  },

  
  /**
   * 
   * @param {string} url 解析文件的服务器地址
   * @param {string} filePath 解析图片/视频的本地路径
   * @param {string} index 当前解析图片/视频的索引
   * @param {object} formData 请求中其他额外的参数
   */
  // 上传图片到服务器解析返回结果
  uploadPicResponse(url, filePath, index, formData){
    console.log(formData);
    console.log(filePath);
    //上传图片到服务器
    const uploadTask = wx.uploadFile({
      url, //上传服务器地址
      filePath, //要上传文件资源的路径(本地路径)
      name: 'file',
      // header: {
      //   Authorization: 'Bearer ' + wx.getStorageSync('token')
      // },
      formData,
      timeout: 5*60*1000,
      //上传成功回调
      success: (res) => {
        console.log(res)
        var data = JSON.parse(res.data);
        console.log(index, data);
        const uploadList = this.data.uploadList
        if (data.code === 200) {
          console.log(data.data);
          // const newUploadList = uploadList.map((fileItem, fileIndex) => {
          //   let newFileItem = fileItem
          //   if (fileIndex === index) {
          //     newFileItem = {
          //       ...fileItem, 
          //       backThumbUrl: data.data,
          //       // progress: 100
          //     }
          //   }
          //   return newFileItem
          // })
          // this.setData({uploadList: newUploadList})

          if (uploadList[index].progress === 99.99) {
            let filterProgressArr = []
            const newUploadList = uploadList.map((fileItem, fileIndex) => {
              filterProgressArr.push(fileItem.progress)
              let newFileItem = fileItem
              if (fileIndex === index) {
                newFileItem = {
                  ...fileItem, 
                  backThumbUrl: data.data,
                  progress: 100
                }
              }
              return newFileItem
            })
            
            // app.globalData.uploadList = newUploadList
            // this.setData({uploadList: newUploadList})
            this.data.uploadList = newUploadList

            this.getMediaList()
          }
        }else if(data.code === 500){
          const newUploadList = uploadList.map((fileItem, fileIndex) => {
            let newFileItem = fileItem
            if (fileIndex === index) {
              newFileItem = {
                ...fileItem, 
                backThumbUrl: data.data,
                progress: -1
              }
            }
            return newFileItem
          })
          // app.globalData.uploadList = newUploadList
          // this.setData({uploadList: newUploadList})
          this.data.uploadList = newUploadList

          this.getMediaList()

        }
      },
      //上传失败回调
      fail: (err) => {
        wx.showToast({
          title: '服务异常',
          icon: 'none'
        })
        console.log(err);
      },
      complete: (completeRes) => {
        console.log(completeRes);
        console.log(this.data.uploadList);
      }
    })

    // 监听上传的进度
    uploadTask.onProgressUpdate(res => {
      // console.log(res.progress);
      const newUploadList = this.data.uploadList
      newUploadList[index].progress = res.progress //上传进度
      if (res.progress === 100) {
        newUploadList[index].progress = 99.99 //上传进度
      }
      app.globalData.uploadList = newUploadList
      // this.setData({uploadList: newUploadList})
      this.data.uploadList = newUploadList
    })

    // 取消上传
    // uploadTask.abort() 
  },

    /**
   * 图片、视频预览
   */
  previewMedia(e){
    const {sources, index} = e.currentTarget.dataset
    const url = sources[index].fileUrl || sources[index].thumbnailUrl
    wx.previewMedia({
      sources: [{url, type: sources[index].fileType}],
      // sources: sources.slice(index, 30).map(source => {
      //   return {
      //     url: source.fileUrl || source.thumbnailUrl,
      //     type: source.fileType
      //   }
      // }),
      current: 0,
      fail: function () {
        wx.showToast({ title: '预览失败', icon: 'none' });
      },
    });
  },

  // 从客户端选择文件
  chooseFileUpload() {
    // 从客户端会话选择文件。
    wx.chooseMessageFile({
      count: 100,
      type: 'all', //all 从所有文件选择  video 视频  image 图片  file 除视频/图片外的文件
      success: (res) => {
        console.log(res);
        const uploadList = res.tempFiles.map(tempFile => {
          return {
            ...tempFile,
            tempFilePath: tempFile.path,
            fileType: tempFile.type
          }
        })
        console.log(uploadList);
        // wx.navigateTo({
        //   url: `/pages/file-processing/index?uploadList=${JSON.stringify(uploadList)}`,
        // })
      },
      fail: err => {
        console.log('chooseMessageFile',err)
      }
    })
  },

  
})